package com.soikc.kuaidiE.mvc;


import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Method;


@WebServlet(urlPatterns = {"/api/*", "/express/*"})
public class DispatcherServlet extends HttpServlet {
    @Override
    public void init(ServletConfig config) {
        //类加载器根目录
        File file = new File(DispatcherServlet.class.getResource("/").getPath());
        String configPath = config.getServletContext().getInitParameter("configPath");
        try {
            FileInputStream fileInputStream = new FileInputStream(new File(file, configPath));
            HandLerMapping.load(fileInputStream);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("加载配置出错了");
        }


    }

    @Override
    public void destroy() {

    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String url = req.getRequestURI();
        System.out.println("收到请求:" + url);
        HandLerMapping.MVCMapping mvcMapping = HandLerMapping.get(url);
        if (mvcMapping == null) {
            resp.sendError(404, "地址不存在" + url);
            return;
        }
        Object obj = mvcMapping.getObj();
        Method method = mvcMapping.getMethod();
        Object str = "";
        try {
            str = method.invoke(obj, req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }

        switch (mvcMapping.getType()) {
            case TEXT:
                resp.getWriter().write(String.valueOf(str));
                break;
            case VIEW:
                resp.sendRedirect(String.valueOf(str));
                break;
        }
    }

}
